package com.sjzd.meeting.controller;

import com.sjzd.weixin.service.MessageService;
import com.sjzd.weixin.utils.SignatureUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

@Controller
@RequestMapping("weixin")
public class WxController {

    private static final Logger log = LoggerFactory.getLogger(WxOauthController.class);
    @Value("${wx.token}")
    private String token;

    @Autowired
    private MessageService ms;

    @Value("${wx.domainName}")
    private String domainName;

    /**
     *  测试用：检查与微信服务器是否正确接入
     * @param req
     * @param resp
     */
    @GetMapping("/")
    public void test(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String signature = req.getParameter("signature");
        String timestamp = req.getParameter("timestamp");
        String nonce = req.getParameter("nonce");
        String echostr = req.getParameter("echostr");

        // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
        boolean flag = SignatureUtils.checkSignature(signature, timestamp, nonce, token);
        if (flag) {
                PrintWriter out = null;
                out = resp.getWriter();
                out.print(echostr);
                out.close();
        }
    }

    /**
     *  处理用户发来的各种类型信息
     * @param req
     * @param resp
     */
    @PostMapping("/")
    public void processMessage(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        try {
            req.setCharacterEncoding("UTF-8");
            resp.setCharacterEncoding("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        String result = ms.processRequest(req);
        PrintWriter out = null;
        out = resp.getWriter();
        out.print(result);
        out.close();
    }

    /**
     *  跳转到错误页面
     * @return
     */
    @GetMapping("/error")
    public String error(@RequestParam(defaultValue = "") String errorMsg, Model model) {
        model.addAttribute("errorMsg", errorMsg);
        return "error";
    }

    /**
     *  测试页面
     * @return
     */
    @GetMapping("/index")
    public String index() {
        return "weixin/index";
    }
}
